import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import TreeMenu from '@/pages/KnowledgeManagement/Overview/ClassifyTree/treeMenu';
import {
  Row,
  Col,
  Card,
  Button,
  Input,
  Modal,
  message,
  Drawer,
  Icon,
  Tree,
  Menu,
  Divider,
  Form,
  TreeSelect,
  Popconfirm,
} from 'antd';
import FormItem from 'antd/lib/form/FormItem';
import TreeWithContextMenu from './TreeWithContextMenu';
import styles from './index.less';

const TreeNodes = TreeSelect.TreeNode;
const { TreeNode } = Tree;
const { confirm } = Modal;

class ClassifyTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      classifyTree: props.treeData,
      rightClickNodeTreeItem: {
        pageX: '',
        pageY: '',
        id: '',
        categoryName: '',
        display: 'none',
      },
      selectedKeys: null,
      disabled: null,
      showModel: false,
      modalTitle: '',
      modalFields: '',
      moveShow: false,
      isDisabled: 0,
      contextMenus: [
        {
          icon: 'plus',
          name: '添加分类',
          key: 'add',
        },
        {
          icon: 'delete',
          name: '删除分类',
          key: 'del',
        },
        {
          icon: 'edit',
          name: '修改分类',
          key: 'alter',
        },
        {
          icon: 'pause-circle',
          name: '停用分类',
          key: 'off',
        },
        {
          icon: 'play-circle',
          name: '启用分类',
          key: 'on',
        },
        {
          icon: 'arrow-up',
          name: '上移分类',
          key: 'up',
        },
        {
          icon: 'arrow-down',
          name: '下移分类',
          key: 'down',
        },
        {
          icon: 'swap',
          name: '移动分类',
          key: 'move',
        },
      ],
    };
  }

  componentDidMount() {}

  loop = data =>
    data.map(item => {
      if (item.children) {
        if (item.data.disabled) {
          return (
            <TreeNode
              key={item.id}
              title={item.text}
              className="disabledClass"
              data={item.data}
              isShared={item.isShared}
              value={item.id}
            >
              {this.loop(item.children)}
            </TreeNode>
          );
        }
        return (
          <TreeNode
            key={item.id}
            title={item.text}
            data={item.data}
            isShared={item.isShared}
            value={item.id}
          >
            {this.loop(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          key={item.id}
          title={item.text}
          data={item.data}
          isShared={item.isShared}
          value={item.id}
        />
      );
    });

  onSelect = (selectedKeys, info) => {
    const selectMenu = selectedKeys[0];
    const disabled = info.node.props.data.disabled;
    let { contextMenus } = this.state;

    this.setState({ selectedKeys: selectMenu });
    this.hideRight('none');
    const treeData = {
      isShared: info.node.props.isShared,
      data: info.node.props.data,
      title: info.node.props.title,
      id: info.node.props.value,
    };
    this.props.onClick(treeData);
  };

  onRightClick = e => {
    const positionInfo = e.event.currentTarget.getBoundingClientRect();
    const x = positionInfo.right - 20;
    const y = positionInfo.bottom;
    this.setState({
      rightClickNodeTreeItem: {
        pageX: x,
        pageY: y,
        id: e.node.props.eventKey,
        path: e.node.props.data.path,
        display: 'block',
        title: e.node.props.title,
        parentPath: e.node.props.data.parentPath,
        nodeDisabled: e.node.props.data.disabled,
      },
      isDisabled: e.node.props.data.disabled ? 1 : 0,
    });
  };

  // 点击取消隐藏
  hideRight = e => {
    const { rightClickNodeTreeItem } = this.state;
    rightClickNodeTreeItem.display = e;
    this.setState({
      rightClickNodeTreeItem,
    });
  };

  handleMenuClick = e => {

  };

  // 菜单右键功能返回
  callbackChild(data) {

    let { rightClickNodeTreeItem, isDisabled } = this.state;
    isDisabled = data.props.data.disabled ? 1 : 0;
    rightClickNodeTreeItem.id = data.props.id;
    rightClickNodeTreeItem.path = data.props.data.path;
    rightClickNodeTreeItem.parentPath = data.props.data.parentPath;
    rightClickNodeTreeItem.title = data.props.text;
    rightClickNodeTreeItem.nodeDisabled = data.props.data.disabled;
    this.setState({
      isDisabled,
      rightClickNodeTreeItem,
    });
    if (data.props.key === 'add') {
      this.setState({
        showModelA: true,
        modalTitle: formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.addCategory' }),
        modalFields: 'addName',
      });
    }
    if (data.props.key === 'del') {
      const that = this;
      confirm({
        title: '删除任务',
        content: '确定要删除吗？',
        onOk() {
          that.deleteCategory();
        },
        onCancel() {

        },
      });
    }
    if (data.props.key === 'alter') {
      this.setState({
        showModelA: true,
        modalTitle: formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.editNodeName' }),
        modalFields: 'businessName',
      });
    }
    if (data.props.key === 'move') {
      this.setState({
        moveShow: true,
      });
    }
    if (data.props.key === 'off' || data.props.key === 'on') {
      this.disableCategory();
    }
    if (data.props.key === 'up') {
      this.upOrDownCategory(0);
    }
    if (data.props.key === 'down') {
      this.upOrDownCategory(1);
    }
  }

  upOrDownCategory = number => {
    // 上移
    const { dispatch } = this.props;
    const { rightClickNodeTreeItem } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'leftTree/upOrDownCategory',
        payload: { path: rightClickNodeTreeItem.path, type: number },
        callback: res => {

          if (res.status === true) {
            message.success(`${res.msg}`);
            this.props.getClass();
          }
        },
      });
    });
  };

  disableCategory = () => {
    const { dispatch, currentUser } = this.props;
    const { rightClickNodeTreeItem, isDisabled } = this.state;
    const that = this;
    if (!rightClickNodeTreeItem.nodeDisabled) {
      // nodeDisabled为false，可停用分类
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'leftTree/knowledgeDisable',
          payload: { targetRobotId: currentUser.robotId, categoryId: rightClickNodeTreeItem.id },
          callback: res => {

            if (res.status === true) {
              message.success(`${res.msg}`);
              that.props.refresh(2);
              that.setState({ isDisabled: 1 });
              that.props.getClass(true);
              that.hideRight('none');
            }
          },
        });
      });
    } else {
      this.reqRef = requestAnimationFrame(() => {
        const that = this;
        dispatch({
          type: 'leftTree/knowledgeEnable',
          payload: { targetRobotId: currentUser.robotId, categoryId: rightClickNodeTreeItem.id },
          callback: res => {

            if (res.status === true) {
              that.props.refresh(1);
              message.success(`${res.msg}`);
              that.setState({ isDisabled: 0 });
              that.props.getClass(true);
              that.hideRight('none');
            }
          },
        });
      });
    }
  };

  deleteCategory = () => {
    // 删 除
    const { dispatch } = this.props;
    const { rightClickNodeTreeItem } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'leftTree/deleteClassify',
        payload: { path: rightClickNodeTreeItem.path },
        callback: res => {

          if (res.status === true) {
            message.success(`${res.msg}`);
            this.props.getClass();
          }
        },
      });
    });
  };

  addName = () => {
    // 添加分类名 addClassify
    const userInfo = this.props.form.getFieldsValue();
    this.props.form.validateFields((err, values) => {
      if (!err) {

        const str = userInfo.addName;
        const val = str.replace(/\s*/g, '');
        const Regx = /^[A-Za-z0-9\u4e00-\u9fa5]*$/;
        if (Regx.test(val)) {
          if (val.length < 21) {
            const a = str.replace(/\s*/g, '');
            const { dispatch } = this.props;
            const { rightClickNodeTreeItem } = this.state;
            this.reqRef = requestAnimationFrame(() => {
              dispatch({
                type: 'leftTree/addClassify',
                payload: { category: a, parentPath: rightClickNodeTreeItem.path },
                callback: res => {

                  if (res.status === true) {
                    this.props.form.setFields({ addName: '' });
                    message.success(`${res.msg}`);
                    this.setState({ showModelA: false });
                    this.props.getClass();
                  }
                },
              });
            });
          } else {
            message.error('分类名称不能为空，不能含有特殊字符，且长度不大于20！操作失败');
          }
        } else {
          message.error('分类名称不能为空，不能含有特殊字符，且长度不大于20！操作失败');
        }
      }
    });
  };

  businessWay = () => {
    // 修改节点名
    const userInfo = this.props.form.getFieldsValue();
    this.props.form.validateFields((err, values) => {

      const { dispatch } = this.props;
      const { rightClickNodeTreeItem } = this.state;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'leftTree/ClassifyName',
          payload: {
            name: userInfo.businessName,
            parentPath: rightClickNodeTreeItem.parentPath,
            cid: rightClickNodeTreeItem.id,
          },
          callback: res => {

            if (res.status === true) {
              this.props.form.setFields({ businessName: '' });
              message.success(`${res.msg}`);
              this.setState({ showModelA: false, title: userInfo.businessName });
              this.props.getClass();
            }
          },
        });
      });
      if (!err) {
      }
    });
  };

  moveShowmove = () => {
    const { dispatch } = this.props;
    const { moveid, rightClickNodeTreeItem } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'leftTree/moveClassify',
        payload: { pid: moveid, cid: rightClickNodeTreeItem.id },
        callback: res => {

          if (res.status === true) {
            message.success(`${res.msg}`);
            this.setState({ moveShow: false, value: '' });
            this.props.getClass();
          }
        },
      });
    });
  };

  // 移动分类
  onChangemove = (value, label, extra) => {

    this.setState({
      value,
      parentPathMove: extra.triggerNode.props.data.parentPath,
      moveid: value,
    });
  };

  onSelects = (selectedKeys, info) => {
    const selectedKey = selectedKeys;

    if (selectedKey) {
      this.setState({ moveid: info.props.eventKey });
    }
  };

  fixMenus = contextMenus => {

    this.setState({
      contextMenus,
    });
  };

  render() {
    const { treeData } = this.props;
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        xs: 24,
        sm: 5,
      },
      wrapperCol: {
        xs: 24,
        sm: 19,
      },
    };
    return (
      <Suspense fallback={<PageLoading />}>
        <div style={{ padding: 10, fontWeight: 800 }}>知识点分类</div>
        {/* <Tree
          showLine
          switcherIcon={<Icon type="down" />}
          onSelect={this.onSelect}
          onRightClick={this.onRightClick}
        >
          {this.loop(treeData.list)}
        </Tree>
        <TreeMenu
          rightClickNodeTreeItem={this.state.rightClickNodeTreeItem}
          hideMenu={this.hideRight}
          callbackChild={this.callbackChild.bind(this)}
          isDisabled={this.state.isDisabled}
        /> */}
        <TreeWithContextMenu
          dataSource={treeData.list}
          onSelect={this.onSelect}
          contextMenus={this.state.contextMenus}
          onHandle={this.callbackChild.bind(this)}
          fixdMenu={this.fixMenus}
        />
        <Modal
          className="modelZdy"
          title={this.state.modalTitle}
          visible={this.state.showModelA}
          okText={<FormattedMessage id="app.customDictionary.save" />}
          cancelText={<FormattedMessage id="app.customDictionary.cancel" />}
          onCancel={() => {
            const that = this;
            if (this.state.modalFields === 'addName') {
              that.props.form.setFields({ addName: '' });
            } else {
              that.props.form.setFields({ businessName: '' });
            }
            this.setState({ showModelA: false });
          }}
          onOk={() => {
            const that = this;
            if (this.state.modalFields === 'addName') {
              that.addName();
            } else {
              that.businessWay();
            }
          }}
        >
          <Form id="add">
            {this.state.modalFields === 'addName' ? (
              <FormItem label={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.addCategoryName' })} onSubmit={this.coreWordOne} {...FormItemLayont}>
                {getFieldDecorator('addName', {
                  initialValue: '',
                  rules: [{ required: true, message: formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.categoryNameRequired' }) }],
                })(<Input onPressEnter={this.addName} autoFocus />)}
              </FormItem>
            ) : (
              <FormItem label={formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.newNodeName' })} {...FormItemLayont}>
                {getFieldDecorator('businessName', {
                  initialValue: this.state.rightClickNodeTreeItem.title,
                  rules: [{ required: true, message: formatMessage({ id: 'knowledgeManagement.overview.editingKnowledge.nodeNameRequired' }) }],
                })(<Input onPressEnter={this.businessWay} autoFocus />)}
              </FormItem>
            )}
          </Form>
        </Modal>
        <Modal
          className="modelZdy"
          title={formatMessage({ id: 'knowledgeFile.fileList.modal.moveCategory.title' })}
          visible={this.state.moveShow}
          okText={<FormattedMessage id="app.customDictionary.save" />}
          cancelText={<FormattedMessage id="app.customDictionary.cancel" />}
          onCancel={() => {
            this.props.form.setFields({ addName: '' });
            this.setState({ moveShow: false });
          }}
          onOk={this.moveShowmove}
        >
          <Form layout="horizontal">
            <FormItem label={formatMessage({ id: 'knowledgeFile.fileList.label.moveToCategory' })} {...FormItemLayont}>
              <TreeSelect
                showSearch
                style={{ width: 300 }}
                value={this.state.value}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder={formatMessage({ id: 'knowledgeFile.fileList.error.selectCategory' })}
                allowClear
                treeDefaultExpandAll
                onChange={this.onChangemove}
                // onSelect={this.onSelects}
              >
                {this.loop(treeData.list)}
              </TreeSelect>
            </FormItem>
          </Form>
        </Modal>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(ClassifyTree));
